// pages/mine/qrcode/index.js

const service = require('../../../service/port')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    canvas: null,
    downLoadData: '',
    qrcodeData: '', //图片的base64地址
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.showLoading({
      title: '生成图片中',
    })
    const query = wx.createSelectorQuery()
    query.select('#qrCodeId')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        let userId = wx.getStorageSync("userInfo").id;
        let param = {
          id: userId || 1
        }
        service.getUserQRCode(param, ({
          data
        }) => {
          console.log(1111, data)
          this.drawCanvas(res, data)
        })
      })
  },

  drawCanvas(res, qr) {

    const dpr = wx.getSystemInfoSync().pixelRatio
    const width = res[0].width * dpr
    const height = res[0].height * dpr

    const canvas = res[0].node

    this.setData({
      canvas: canvas
    })
    canvas.width = width
    canvas.height = height


    const ctx = canvas.getContext('2d')
    // ctx.scale(dpr, dpr)

    //绘制背景图片
    let bgImage = canvas.createImage()
    const bgImageDpr = 375 / 731

    bgImage.src = 'https://hopermall.oss-cn-beijing.aliyuncs.com/renrenbo/qr_bg.png'
    // bgImage.width = width
    // bgImage.height = width / bgImageDpr
    bgImage.onload = () => {
      ctx.fillStyle = '#ffffff'
      ctx.fillRect(0, 0, width, height)
      ctx.drawImage(bgImage, 0, 0, width, width / bgImageDpr)


      //绘制二维码图片
      let qrImage = canvas.createImage()
      qrImage.src = qr
      // qrImage.width = 200
      // qrImage.height = 200
      qrImage.onload = (res) => {

        //绘制二维码背景
        let rectW = 250 * dpr
        let rectH = 250 * dpr
        let rectX = (width - rectW) / 2
        let rectY = (height - rectH) / 2
        //设置阴影
        ctx.shadowOffsetX = 20
        ctx.shadowOffsetY = 20
        ctx.shadowColor = 'rgba(201,201,201,0.3)'
        ctx.shadowBlur = 100
        this.strokeRoundRect(ctx, rectX, rectY, rectW, rectH, 20)
        //绘制二维码图片
        let qrImageW = 150 * dpr
        let qrImageH = 150 * dpr
        let qrImageX = (width - qrImageW) / 2
        let qrImageY = (height - qrImageH) / 2 - 30
        ctx.drawImage(qrImage, qrImageX, qrImageY, qrImageW, qrImageH)
        //画虚线
        ctx.setLineDash([5, 5]);
        ctx.strokeRect(qrImageX, qrImageY, qrImageW, qrImageH);
        // this.drawImageBorder(ctx)
        //绘制文字
        let fontText = '邀好友 得收益'
        ctx.font = '50px Arial';
        ctx.fillStyle = "#F8584B"

        let measure = ctx.measureText(fontText)
        let fontX = (width - measure.width) / 2
        let fontY = 170
        ctx.fillText(fontText, fontX, fontY);

        let fontText2 = '随时随地 分享精彩生活'
        ctx.font = '42px Arial';
        ctx.fillStyle = "#333333"

        let measure2 = ctx.measureText(fontText2)
        let fontX2 = (width - measure2.width) / 2
        let fontY2 = 250
        ctx.fillText(fontText2, fontX2, fontY2);

        ctx.save()

        let fontText3 = '长按保存二维码'
        ctx.font = '32px Arial';
        ctx.fillStyle = "#999999"

        let measure3 = ctx.measureText(fontText3)
        let fontX3 = (width - measure3.width) / 2
        let fontY3 = qrImageY + qrImageH + 75
        ctx.fillText(fontText3, fontX3, fontY3);


        let fontText4 = '点击右上角 - 更多 - 发送给朋友 - 即可分享'
        ctx.font = '32px Arial';
        ctx.fillStyle = "#2B8644"

        let measure4 = ctx.measureText(fontText4)
        let fontX4 = (width - measure4.width) / 2
        let fontY4 = height - 100
        ctx.fillText(fontText4, fontX4, fontY4);

        ctx.restore()

        wx.hideLoading({})
      }
      qrImage.onerror = (err) => {
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              title: '加载图片失败了!',
              icon : 'none'
            })
          },
        })
      }
    }
  },

  wxSageFileToLocal(base64) {

  },

  saveImage() {
    //当前页面绘制图片
    let _this = this
    let canvas = this.data.canvas
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      // width: 600,
      // height: 922,
      // destWidth: 600,
      // // quality: 1,
      // destHeight: 922,
      canvas,
      success({
        tempFilePath
      }) {
        wx.saveImageToPhotosAlbum({
          filePath: tempFilePath,
          success() {
            wx.showToast({
              title: '保存成功!',
            })
          },
          fail(err) {
            console.log(22222, err)
            if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
              wx.showModal({
                title: '提示',
                content: '需要您授权保存相册',
                showCancel: false,
                success: modalSuccess => {
                  wx.openSetting({
                    success(settingdata) {
                      console.log("settingdata", settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限成功,再次点击图片即可保存',
                          showCancel: false,
                        })
                      } else {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限失败，将无法保存到相册哦~',
                          showCancel: false,
                        })
                      }
                    },
                    fail(failData) {
                      console.log("failData", failData)
                    },
                    complete(finishData) {
                      console.log("finishData", finishData)
                    }
                  })
                }
              })
            }
          }
        })
      },

    }, this)




  },
  strokeRoundRect(cxt, x, y, width, height, radius, lineWidth, strokeColor) {
    //圆的直径必然要小于矩形的宽高          
    if (2 * radius > width || 2 * radius > height) {
      return false;
    }

    cxt.save();
    cxt.translate(x, y);
    //绘制圆角矩形的各个边  
    this.drawRoundRectPath(cxt, width, height, radius);
    cxt.lineWidth = lineWidth || 2; //若是给定了值就用给定的值否则给予默认值2  
    cxt.strokeStyle = strokeColor || "#ffffff";
    cxt.fill();
    cxt.stroke();
    cxt.restore();
  },
  drawRoundRectPath(cxt, width, height, radius) {
    cxt.beginPath(0);
    //从右下角顺时针绘制，弧度从0到1/2PI  
    cxt.arc(width - radius, height - radius, radius, 0, Math.PI / 2);

    //矩形下边线  
    cxt.lineTo(radius, height);

    //左下角圆弧，弧度从1/2PI到PI  
    cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);

    //矩形左边线  
    cxt.lineTo(0, radius);

    //左上角圆弧，弧度从PI到3/2PI  
    cxt.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);

    //上边线  
    cxt.lineTo(width - radius, 0);

    //右上角圆弧  
    cxt.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);

    //右边线  
    cxt.lineTo(width, height - radius);
    cxt.closePath();
  },

  onShareAppMessage: function () {

  }
})